<template>
  <v-container fluid>
    <v-row justify="center">
      <v-col sm="4" md="4" lg="3">
        <v-card>
          <v-img src="../assets/login/background.png" class="white--text align-center" alt="邮箱修改">
            <v-card-title>邮箱修改</v-card-title>
          </v-img>
          <v-form ref="emailForm" v-model="valid" lazy-validation>
            <v-card-text>
              <v-text-field v-model="user.email" :rules="emailRules" label="邮箱"></v-text-field>
              <!--保存按钮-->
              <v-btn :disabled="!valid" color="primary" class="mr-4" v-on:click="validate">保存</v-btn>
            </v-card-text>
          </v-form>
        </v-card>
      </v-col>
    </v-row>
    <v-snackbar
      v-model="snackbar"
    >
      邮箱修改成功
      <template v-slot:action="{ attrs }">
        <v-btn
          color="pink"
          text
          v-bind="attrs"
          @click="snackbar = false"
        >
          Close
        </v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<script>
export default {
  name: 'Email',
  data: () => ({
    snackbar: false,
    valid: true,
    user: {
      email: ''
    },
    emailRules: [
      v => !!v || '请输入邮箱',
      v => /(\w+)@(\w+)\.(\w+)/.test(v) || '邮箱格式不正确'
    ]
  }),
  methods: {
    validate () {
      const valid = this.$refs.emailForm.validate()
      if (valid) {
        this.$axios.patch('rest_auth/user/', {
          email: this.user.email
        }).then(response => {
          console.log(response)
          // 重新设置state.user
          this.$store.commit('setUser', response.data)
          // 提示邮箱修改成功
          this.snackbar = true
        }).catch(error => {
          console.log(error)
        })
      }
    }
  },
  created () {
    this.user.email = this.$store.state.user.email ? this.$store.state.user.email : ''
  }
}
</script>

<style scoped>

</style>
